package com.example.pt.mapper;

import com.example.pt.entity.PrivateMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.Date;
import java.util.List;

/**
 * 私信Mapper接口
 */
@Mapper
public interface PrivateMessageMapper extends BaseMapper<PrivateMessage> {
    
    /**
     * 查询与指定用户的历史聊天记录（30天内）
     * @param conversationId 会话ID
     * @param days 天数，默认30天
     * @return 私信列表
     */
    @Select("SELECT * FROM private_message WHERE conversation_id = #{conversationId} AND create_time >= DATE_SUB(NOW(), INTERVAL #{days} DAY) AND status != 2 ORDER BY create_time ASC")
    List<PrivateMessage> selectMessagesByConversationId(@Param("conversationId") String conversationId, @Param("days") Integer days);
    
    /**
     * 查询用户的未读消息数
     * @param userId 用户ID
     * @param conversationId 会话ID，可选
     * @return 未读消息数
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM private_message WHERE receiver_id = #{userId} AND status = 0 " +
            "<if test='conversationId != null'> AND conversation_id = #{conversationId} </if>" +
            "</script>")
    int countUnreadMessages(@Param("userId") Integer userId, @Param("conversationId") String conversationId);
    
    /**
     * 将消息标记为已读
     * @param messageId 消息ID
     * @return 影响行数
     */
    @Update("UPDATE private_message SET status = 1 WHERE message_id = #{messageId}")
    int markMessageAsRead(@Param("messageId") Integer messageId);
    
    /**
     * 将会话中的所有消息标记为已读
     * @param userId 用户ID（接收者）
     * @param conversationId 会话ID
     * @return 影响行数
     */
    @Update("UPDATE private_message SET status = 1 WHERE receiver_id = #{userId} AND conversation_id = #{conversationId} AND status = 0")
    int markConversationAsRead(@Param("userId") Integer userId, @Param("conversationId") String conversationId);
    
    /**
     * 查询用户的会话列表（最新消息）
     * @param userId 用户ID
     * @return 私信列表
     */
    @Select("SELECT p.* FROM private_message p " +
            "INNER JOIN (" +
            "   SELECT conversation_id, MAX(create_time) as max_time " +
            "   FROM private_message " +
            "   WHERE (sender_id = #{userId} OR receiver_id = #{userId}) AND status != 2 " +
            "   GROUP BY conversation_id" +
            ") t ON p.conversation_id = t.conversation_id AND p.create_time = t.max_time " +
            "ORDER BY p.create_time DESC")
    List<PrivateMessage> selectLatestMessagesByUserId(@Param("userId") Integer userId);
} 